package com.project.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.demo.dao.UserMapper;
import com.project.demo.entity.User;
import com.project.demo.entity.UserFile;
import com.project.demo.service.UserFileService;
import com.project.demo.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("userFile")
public class UserFileController {
    @Resource
    private UserFileService userFileService;

    @Resource
    TokenUtils tokenUtils;

    @GetMapping
    public IPage<UserFile> pageList(UserFile userFile){
        return userFileService.pageList(userFile);
    }

    @PostMapping("/addUserFile")
    public Map<String, Object> add(MultipartFile file) throws Exception {
        User user = tokenUtils.getUserIdByRequest();
        return userFileService.add(file,user.getUserPrivateKey());
    }

    @PostMapping("/uploadCeleu")
    public Map<String, Object> uploadCeleu(MultipartFile file) throws Exception {
        return null;
    }

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response,String filePath,String fileName,String publicKey,String secretKey){
        userFileService.download(request,response,filePath,fileName,publicKey,secretKey);
    }

    public Map<String,Object> readBody(BufferedReader reader){
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try{
            br = reader;
            String str;
            while ((str = br.readLine()) != null){
                sb.append(str);
            }
            br.close();
            String json = sb.toString();
            return JSONObject.parseObject(json, Map.class);
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if (null != br){
                try{
                    br.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
